<template>
  <NavbarComponent />
  <div class="post-container">
    <el-card class="post-card">
      <h2 class="title">发布闲置</h2>
      <el-form 
        :model="form" 
        label-width="120px" 
        label-position="top" 
        :rules="rules" 
        ref="formRef"
      >
        <!-- 商品类别 -->
        <el-form-item label="商品类别" prop="category">
          <el-select 
            v-model="form.category"
            multiple
            filterable
            placeholder="请选择商品分类"
            class="category-select"
            @change="handleCategoryChange"
          >
            <el-option
              v-for="item in categories"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <!-- 教材信息 -->
        <div >
          <el-form-item label="年级" prop="grade">
            <el-select
              v-model="form.grade"
              placeholder="请选择年级"
              class="grade-select"
              clearable
            >
              <el-option
                v-for="grade in grades"
                :key="grade"
                :label="grade"
                :value="grade"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="专业" prop="major">
            <el-autocomplete
              v-model="form.major"
              :fetch-suggestions="querySearch"
              placeholder="请输入或选择专业"
              class="major-select"
              :loading="majorsLoading"
              @select="handleSelectMajor"
            >
              <template #prefix>
                <el-icon><Collection /></el-icon>
              </template>
            </el-autocomplete>
          </el-form-item>
        </div>
        <el-form-item label="学校" prop="school">
  <el-autocomplete
    v-model="form.school"
    :fetch-suggestions="fetchSchools"
    clearable
    placeholder="请输入或选择学校"
    class="school-select"
    :loading="schoolsLoading"
    @select="handleSelectSchool"
  >
    <template #prefix>
      <el-icon><School /></el-icon>
    </template>
  </el-autocomplete>
</el-form-item>

        <!-- 商品名称 -->
        <el-form-item label="商品名称" prop="productName">
          <el-input 
            v-model="form.productName" 
            placeholder="请输入商品名称"
            class="custom-input"
            clearable
          >
            <template #prefix>
              <el-icon><Goods /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 商品价格 -->
        <el-form-item label="商品价格（元）" prop="price">
          <el-input 
            v-model="form.price"
            placeholder="请输入价格"
            class="price-input"
            @input="validatePrice"
          >
            <template #prefix>
              <el-icon><Money /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 商品介绍 -->
        <el-form-item label="商品介绍" prop="introduction">
          <el-input
            v-model="form.introduction"
            type="textarea"
            :rows="4"
            placeholder="请输入商品详细信息（成色、规格、使用情况等）"
            class="description-input"
            resize="none"
            show-word-limit
            maxlength="300"
          />
        </el-form-item>
        <!-- 销售类型  -->
        <el-form-item label="销售类型" prop="saleType">
          <div class="auction-switch">
            <el-switch
            v-model="form.saleType"
            :active-value="1"
            :inactive-value="0"
            active-text="竞拍商品"
            inactive-text="普通商品"
            inline-prompt
      style="--el-switch-on-color: #409eff; --el-switch-off-color: #909399"
            />
            <div v-if="form.saleType === 1" class="auction-tip">
              <el-icon><InfoFilled /></el-icon>
              <span>设置为竞拍商品后，买家将参与竞价购买</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item 
          label="竞拍开始时间" 
          prop="auctionStartTime"
          v-if="form.saleType === 1"
        >
          <el-date-picker
            v-model="form.auctionStartTime"
            type="datetime"
            placeholder="选择开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item 
          label="竞拍结束时间" 
          prop="auctionEndTime"
          v-if="form.saleType === 1"
        >
          <el-date-picker
            v-model="form.auctionEndTime"
            type="datetime"
            placeholder="选择结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="endDateDisabled"
          />
        </el-form-item>
        <!-- 图片上传 -->
        <el-form-item label="商品图片" prop="images">
          <el-upload
            v-model:file-list="form.images"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="5"
            :on-exceed="handleExceed"
            multiple
            :on-change="handleImageChange"
            class="image-uploader"
          >
            <el-icon><Plus /></el-icon>
            <template #file="{ file }">
              <img :src="file.url" class="uploaded-image" />
              <span class="image-actions">
                <span class="image-preview" @click.stop="handlePictureCardPreview(file)">
                  <el-icon><ZoomIn /></el-icon>
                </span>
                <span class="image-delete" @click.stop="handleRemove(file)">
                  <el-icon><Delete /></el-icon>
                </span>
              </span>
            </template>
          </el-upload>
        </el-form-item>

        <!-- 提交按钮 -->
        <div class="submit-area">
          <el-button 
            type="text" 
            class="draft-btn"
            @click="handleSaveDraft"
            :loading="draftLoading"
          >
            {{ draftLoading ? '保存中...' : '存草稿' }}
          </el-button>
          <el-button 
            type="primary" 
            class="submit-btn"
            @click="handleSubmit"
            :loading="loading"
          >
            {{ loading ? '提交中...' : '立即发布' }}
          </el-button>
        </div>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog v-model="dialogVisible" title="图片预览" width="60%">
      <img :src="previewImageUrl" class="preview-image" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import axios from 'axios'
import NavbarComponent from '@/components/components/NavbarComponent.vue'
import { Goods, Money, Plus, ZoomIn, Delete, Collection,InfoFilled  ,School } from '@element-plus/icons-vue'

// 表单引用
const formRef = ref()

// 响应式数据
const loading = ref(false)
const draftLoading = ref(false)
const dialogVisible = ref(false)
const previewImageUrl = ref('')
const majors = ref([])
const majorsLoading = ref(false)
const schoolsLoading = ref(false)
const schools = ref([])
// 表单数据
const form = reactive({
  category: [],
  productName: '',
  price: '',
  introduction: '',
  images: [],
  grade: '',
  major: '',
  saleType: 0 , // 0:普通商品 1:竞拍商品
 auctionStartTime: null,
  auctionEndTime: null
})

// 静态数据
const grades = ['大一', '大二', '大三', '大四', '研一', '研二', '研三']
const categories = [
  '乐器','数码','艺术品','美妆','书籍',
  '服饰','家居','运动户外','文具','玩具','二手教材'
]

// 计算属性
const showEducationFields = computed(() => 
  form.category.includes('二手教材')
)
const fetchSchools = async (queryString, cb) => {
  if (!queryString) return cb([])
  try {
    schoolsLoading.value = true
    const response = await axios.get('http://localhost:8092/school/list')
    const results = response.data.filter(school => 
      school.schoolname.toLowerCase().includes(queryString.toLowerCase())
    )
    cb(results.map(school => ({ value: school.schoolname })))
  } catch (error) {
    console.error('学校加载失败:', error)
    ElMessage.error('学校列表加载失败')
    cb([])
  } finally {
    schoolsLoading.value = false
  }
}

const handleSelectSchool = (item) => {
  form.school = item.value
}
// 验证规则
const rules = reactive({
  category: [
    { 
      required: true, 
      message: '请至少选择一个商品类别', 
      trigger: 'change',
      type: 'array',
      validator: (rule, value, callback) => {
        value.length === 0 ? callback(new Error('至少选择一个分类')) : callback()
      }
    }
  ],
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在2到30个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { 
      pattern: /^\d+(\.\d{0,2})?$/, 
      message: '请输入有效的价格格式（如：99.99）', 
      trigger: 'blur' 
    }
  ],
  introduction: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { min: 10, message: '至少输入10个字符描述', trigger: 'blur' }
  ],
  images: [
    { 
      required: true, 
      validator: (rule, value, callback) => {
        value.length === 0 ? callback(new Error('请至少上传一张图片')) : callback()
      },
      trigger: 'change'
    }
  ],
  grade: [
    { 
      required: true, 
      message: '请选择年级', 
      trigger: 'change',
      // validator: (rule, value, callback) => {
      //   showEducationFields.value && !value ? callback(new Error('请选择年级')) : callback()
      // }
    }
  ],
  major: [
    { 
      required: true, 
      message: '请选择专业', 
      trigger: 'change',
      // validator: (rule, value, callback) => {
      //   showEducationFields.value && !value ? callback(new Error('请选择专业')) : callback()
      // }
    }
  ],
  saleType: [
    { 
      required: true,
      message: '请选择销售类型',
      trigger: 'change'
    }
  ],
  school: [
    { 
      required: true, 
      message: '请选择学校', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.category.includes('二手教材') && !value) {
          callback(new Error('请选择学校'))
        } else {
          callback()
        }
      }
    }
  ],
  auctionStartTime: [
    { 
      required: true,
      message: '请选择开始时间',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.saleType === 1 && !value) {
          callback(new Error('必须选择开始时间'))
        } else {
          callback()
        }
      }
    }
  ],
  auctionEndTime: [
    { 
      required: true,
      message: '请选择结束时间',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.saleType === 1) {
          if (!value) {
            callback(new Error('必须选择结束时间'))
          } else if (new Date(value) <= new Date(form.auctionStartTime)) {
            callback(new Error('结束时间必须晚于开始时间'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }
  ]
})

// 生命周期钩子
onMounted(async () => {
  await loadMajors()
})

// 方法定义
const validatePrice = (value) => {
  if (!/^\d*\.?\d{0,2}$/.test(value)) {
    form.price = value.slice(0, -1)
  }
}

// const handleCategoryChange = (val) => {
//   if (!val.includes('二手教材')) {
//     form.grade = ''
//     form.major = ''
//   }
// }

const loadMajors = async () => {
  try {
    majorsLoading.value = true
    const { data } = await axios.get('http://localhost:8092/major/list')
    // 确保使用正确的字段名（根据实际接口返回）
    majors.value = data.map(m => ({ 
      value: m.majorName || m.majorname // 根据实际返回字段调整
    }))
    console.log('Loaded majors:', majors.value) // 调试用
  } catch (error) {
    ElMessage.error('专业列表加载失败')
  } finally {
    majorsLoading.value = false
  }
}

const querySearch = (queryString, cb) => {
  const searchString = queryString?.trim().toLowerCase() || ''
  const results = majors.value.filter(m => 
    m.value && m.value.toLowerCase().includes(searchString)
  )
  cb(results.length ? results : majors.value)
}

const handleSelectMajor = (item) => {
  form.major = item.value
}

// 图片处理方法
const handlePictureCardPreview = (file) => {
  previewImageUrl.value = file.url
  dialogVisible.value = true
}

const handleRemove = (file) => {
  const index = form.images.findIndex(f => f.uid === file.uid)
  form.images.splice(index, 1)
}

const handleExceed = () => {
  ElMessage.warning('最多只能上传5张图片')
}

const handleImageChange = (file) => {
  if (!file.raw.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  if (file.raw.size > 10 * 1024 * 1024) {
    ElMessage.error('单张图片大小不能超过10MB')
    return false
  }
  return true
}

// 表单提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true
    
    const formData = new FormData()
    // 基础字段
    formData.append('categories', form.category.join(','))
    formData.append('productName', form.productName)
    formData.append('price', form.price)
    formData.append('introduction', form.introduction)
    
    // 教材相关字段

      formData.append('grade', form.grade)
      formData.append('major', form.major)
      formData.append('saleType', form.saleType)
     formData.append('school', form.school)
    // 图片文件
    form.images.forEach(file => formData.append('images', file.raw))

    // 请求配置
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('请先登录')
      return
    }

    const productRes = await axios.post('http://localhost:8092/product/post', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${token}`
      }
    })

    if (productRes.data.code === 200) {
      if (form.saleType === 1) {
        console.log('productRes', productRes.data.data.productId)
        const formData = new FormData()
        formData.append('productId', productRes.data.data.productId)
        formData.append('startTime', form.auctionStartTime)
        formData.append('endTime', form.auctionEndTime)
        formData.append('price', form.price) // 传递商品价格

        const auctionRes = await axios.post(
          'http://localhost:8092/auction/create',
          formData,
          { headers: { Authorization: `Bearer ${token}` } }
        )
        
        if (auctionRes.data.code !== 200) {
          throw new Error('竞拍创建失败: ' + auctionRes.data.message)
        }
      }
      ElMessage.success({
        message: '发布成功，请等待管理员审核（预计1个工作日内完成）',
        duration: 3000,
        showClose: true
      })
      formRef.value.resetFields()
      form.images = []
      setTimeout(() => window.close(), 3000)
    } else {
      ElMessage.error(response.data.message || '发布失败')
    }
  } catch (error) {
    handleError(error)
  } finally {
    loading.value = false
  }
}



  const handleSaveDraft = async () => {
    try {
      // 执行表单验证
      await formRef.value.validate()
      draftLoading.value = true
      
      // 创建FormData对象
      const formData = new FormData()
      formData.append('categories', form.category.join(','))
      formData.append('productName', form.productName)
      formData.append('price', form.price)
      formData.append('introduction', form.introduction)
      
      // 添加图片文件
      form.images.forEach(file => {
        formData.append('images', file.raw)
      })

      // 获取登录令牌
      const token = localStorage.getItem('token')
      if (!token) {
        ElMessage.error('请先登录')
        return
      }

      // 发送保存草稿请求
      const response = await axios.post(
        'http://localhost:8092/draft/saveDraft',
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': `Bearer ${token}`
          }
        }
      )

      // 处理响应
      if (response.data.code === 200) {
        ElMessage.success({
          message: '草稿保存成功',
          duration: 2000
        })
        // 保留表单内容以便继续编辑
      } else {
        ElMessage.error(response.data.msg || '草稿保存失败')
      }
    } catch (error) {
      // 错误处理
      if (error.response) {
        const status = error.response.status
        if (status === 401) {
          ElMessage.error('登录已过期，请重新登录')
          // 可以跳转到登录页
        } else if (status === 413) {
          ElMessage.error('文件大小超过限制')
        } else {
          ElMessage.error(`保存失败：${error.response.data.msg}`)
        }
      } else if (error.request) {
        ElMessage.error('网络连接异常，请检查网络')
      } else {
        ElMessage.error(`请求错误：${error.message}`)
      }
    } finally {
      draftLoading.value = false
    }
  }

  // 错误处理
  const handleError = (error) => {
    let message = '提交失败'
    if (error.response) {
      message = error.response.data.message || message
    } else if (error.request) {
      message = '网络连接异常'
    }
    ElMessage.error(`${message}: ${error.message}`)
  }
  </script>
  
  <style scoped>
.post-container {
  padding: 40px 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.post-card {
  max-width: 800px;
  margin: 0 auto;
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
}

.title {
  text-align: center;
  color: #303133;
  margin-bottom: 30px;
  font-weight: 600;
  letter-spacing: 1px;
}

.category-select {
  width: 100%;
}

.category-select :deep(.el-tag) {
  margin: 4px;
  background-color: #ecf5ff;
  border-color: #d9ecff;
  color: #409eff;
}

.custom-input {
  width: 100%;
}

.custom-input :deep(.el-input__wrapper) {
  padding: 0 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.price-input {
  width: 100%;
}

.price-input :deep(.el-input__wrapper) {
  padding: 0 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.description-input :deep(.el-textarea__inner) {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
  line-height: 1.5;
  transition: all 0.3s;
}

.image-uploader :deep(.el-upload) {
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  transition: all 0.3s;
  width: 120px;
  height: 120px;
}

.image-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
  background: rgba(64, 158, 255, 0.05);
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}
.auction-switch {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.auction-tip {
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 12px;
  line-height: 1.5;
  
  .el-icon {
    color: #409eff;
    margin-right: 6px;
    font-size: 14px;
  }
}
.image-actions {
  position: absolute;
  right: 8px;
  bottom: 8px;
  display: flex;
  gap: 8px;
}

.image-actions .el-icon {
  background: rgba(0, 0, 0, 0.5);
  padding: 4px;
  border-radius: 4px;
  color: white;
  cursor: pointer;
  transition: all 0.2s;
}

.image-actions .el-icon:hover {
  background: rgba(0, 0, 0, 0.7);
}

.submit-area {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

.draft-btn {
  color: #409eff !important;
  font-size: 14px;
  margin-right: 20px;
  padding: 12px;
  transition: all 0.3s;
}

.draft-btn:hover {
  color: #66b1ff !important;
  transform: translateY(-1px);
}

.submit-btn {
  width: 200px;
  height: 40px;
  font-size: 16px;
  letter-spacing: 1px;
  border-radius: 8px;
  transition: all 0.3s;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.preview-image {
  width: 100%;
  height: 60vh;
  object-fit: contain;
  border-radius: 8px;
}

@media (max-width: 768px) {
  .post-card {
    margin: 0 15px;
  }

  .image-uploader :deep(.el-upload) {
    width: 100px;
    height: 100px;
  }

  .submit-area {
    flex-direction: column;
    gap: 15px;
  }

  .draft-btn {
    margin-right: 0;
    order: -1;
  }

  .submit-btn {
    width: 100%;
  }
}

.submit-btn.is-disabled {
  opacity: 0.7;
  transform: none;
  box-shadow: none;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.submit-btn :deep(.el-icon) {
  animation: spin 1s linear infinite;
  margin-right: 8px;
}
/* 新增专业选择样式 */
.grade-select,
.major-select {
  width: 100%;
  margin-bottom: 20px;
}

.major-select .el-input__prefix {
  padding: 0 8px;
  display: flex;
  align-items: center;
}

.major-select .el-icon {
  font-size: 18px;
  color: #666;
}

@media (max-width: 768px) {
  .major-select {
    margin-top: 10px;
  }
}
.el-form-item[label="商品价格（元）"] label:after {
  content: attr(data-label-suffix);
}
.el-date-editor.el-input {
  width: 100%;
}

.el-date-editor .el-input__inner {
  padding-left: 35px;
}
.school-select {
  width: 100%;
}

.school-select .el-input__prefix {
  padding: 0 8px;
  display: flex;
  align-items: center;
}

.school-select .el-icon {
  font-size: 18px;
  color: #666;
}
</style>